const express = require('express');
const jwt = require('jsonwebtoken')
const users = require('./models/user')
const config = require('./models/config')

const failMsg = {
    status: 'failed',
    code: -1,
    message: 'wrong passwd or username'
}

const acessDenied = {
    status: 'failed',
    code: -2,
    message: 'access denied'
}

const loginVerify = (req, res, next) => {
    // console.log('cookie', req.cookies)
    console.log('token', req.get('Token'))
    let token = req.get('Token')
    if (token) {
        jwt.verify(token, config.secret, (err, data) => {
            if (data && users[data.name] && users[data.name].passwd == data.passwd) {
                next()
            } else {
                // res.redirect('/login')
                res.json(acessDenied)
            }
        })
    } else {
        // res.redirect('/login')
        res.json(acessDenied)
    }
}

const loginHandler = (req, res) => {
    let name = req.body.username
    let passwd = req.body.password
    console.log(req.body)
    if (users[name] && users[name].passwd == passwd) {
        let token = jwt.sign({
            name: name,
            passwd: passwd
        }, config.secret, { expiresIn: '30 days' });
        res.json({
            status: 'success',
            code: 0,
            token: token
        })
    } else {
        res.json(failMsg)
    }
}

module.exports = {
    loginHandler,
    loginVerify
}